package com.tsk.example.listener;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.security.crypto.encrypt.TextEncryptor;

/**
 * @author: 黄嘉振
 * @create: 2023/1/17 17:51
 * @description: 自定义监听器，能与nacos-config适配，可以监听到本地配置及config配置的事件，会对{cipher}开头的内容进行解密
 *          具体可查看 EncryptionBootstrapConfiguration，
 *          同样需要在spring.factories配置
 **/
public class MyListener implements ApplicationListener<ApplicationPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent event) {
        System.out.println("========MyListener======" + event.getClass().getName());
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();
        System.out.println("======context=====" + applicationContext);
        // 这里回往spring IOC 中添加好几次，是因为父子容器的原因，所以要判断一下
        if(applicationContext instanceof AnnotationConfigApplicationContext) {
            ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
            // 这里判断是否已经添加过我们自己的解密算法了，没添加才添加，否则跳过
            if (!beanFactory.containsBean("textEncryptor")) {
                beanFactory.registerSingleton("textEncryptor", new TextEncryptor() {
                    @Override
                    public String encrypt(String text) {
                        System.out.println("=====================================加密");
                        return "加密" + text;
                    }

                    @Override
                    public String decrypt(String encryptedText) {
                        //这里解密就直接输出日志，然后直接解密返回
                        System.out.println("=====================================解密");
//                        return EncryptUtil.decrypt("work0", encryptedText);
                        return "nacos-config:" + encryptedText;
                    }
                });
            }
        }
    }

//    @Override
//    public int getOrder() {
//        return Ordered.HIGHEST_PRECEDENCE;
//    }
}
